const pool=require('../../Model/query')
const {JWT_SECRET,encrypt}=require('../../config/userConfig')
const update=(req, res)=>{
  const id=req.params.id
  let {userName,password,nickName,mobile,avator,sex=2,age}=req.body
  const  sql=`UPDATE user SET
  userName = ?,
  password = ?,
  nickName = ?,
  mobile = ?,
  avator = ?,
  sex = ?,
  updateTime = NOW(),
  age = ?
  WHERE id = ?`
  pool(sql,[userName,encrypt(password),nickName,mobile,avator,sex,age,id])
  .then(res1=>{
    res.send({
      code:200,
      msg:'编辑成功',

    });
  }).catch(()=>{
    res.send({
      code:500,
      msg:'编辑失败'
    });
  })
}
const add=(req, res)=>{
  let {userName,password,nickName,mobile,avator,sex,createTime=NOW()}=req.body
  if(!userName||!password){
    return  res.send({
      code:400,
      msg:'userName和password不能为空'
    });
  }
  const sql1=`SELECT userName  FROM  USER WHERE userName=?`
  password=encrypt(password)
  const sql2 = `INSERT INTO user (
  userName,password,nickName,mobile,avator,sex,createTime)
  VALUES(?,?,?,?,?,?,?)`
  pool(sql1,[userName,password,nickName,mobile,avator,sex,createTime]).then(res1=>{
    console.log(res1.length>0,11);
    if(res1.length>0){
      res.send({
        code:500,
        msg:'账号存在请重新添加'
      });
    }else{
      pool(sql2,[userName,password,nickName,mobile,avator,sex=1,createTime]).then(res2=>{
        res.send({
          code:200,
          msg:'添加成功'
        });
      }).catch(()=>{
        res.send({
          code:500,
          msg:'添加失败'
        });
      })
    }

  }).catch(()=>{
    res.send({
      code:500,
      msg:'添加失败'
    });
  })
}
const del=(req,res)=>{
  const id=req.params.id
  const sql=`DELETE FROM user WHERE id = ?`
  pool(sql,[id]).then(res1=>{
    res.send({
      code:200,
      msg:'删除成功',

    });
  }).catch(()=>{
    res.send({
      code:500,
      msg:'删除失败'
    });
  })
}
const queryUserList=(req,res)=>{
  const {page,pageSize} =req.query
  const sql1=`SELECT count(*) as total from user`
  const offset=(page-1)*pageSize
  const limit=pageSize*1
  const sql2=`SELECT id, "userName", "nickName", "mobile", "avator", "sex", "age", "createTime", "updateTime" FROM user
  ORDER BY id
  LIMIT ?,
  ?`
  pool(sql1).then(res1=>{
    pool(sql2,[offset,limit]).then(res2=>{
      res.send({
        code:200,
        data:{
          currentPage:page*1,
          pageSize:limit,
          total:res1[0].total,
          result:res2
        },
        msg:'查询成功',
      });
    }).catch(()=>{
      res.send({
        code:500,
        msg:'查询失败'
      });
    })
  })

}

module.exports={
  update,
  add,
  del,
  queryUserList
}
